//引入API文件直接进行请求
import * as api from '@/utils/api.js'
import UUID from '@/utils/uuid_token.js'
const state={
    goodInfo:{},
    uuid_token:UUID.getUUID()
};
const mutations={
    GETITEM(state,goodInfo){
        state.goodInfo=goodInfo
    }
};
const actions={
  async getItem({commit},params){
   const {data:res}= await api.getItem(params)
    commit('GETITEM',res)
  },
  async addToCart({commit},params){
    console.log(commit,params)
    const res=await api.addToCart(params.skuID,params.skuNum)
    if (res.code===200) {
        return 'ok'
    }else{
        return Promise.reject(new Error('faile'))
    }
  },
  //选择商品
  async checkCart({commit},params){
    console.log(commit)
    const res=await api.checkCart(params.skuId,params.isChecked)
    if (res.code===200) {
        return 'ok'
    }else{
        return Promise.reject(new Error('faile'))
    }
  },
  //解构拿到整个store中的actions还有getters
  //删除全部商品
   delCheck({dispatch,getters}){
    let PromiseAll=[]
    getters.cartInfoList.forEach(e => {
       let promise= e.isChecked===1 ? dispatch('delCart',e.skuId) : ''
       //将返回的promise存入数组收集起来
       PromiseAll.push(promise)
    });
    //然后一次性全部返回(如果有一个失败那就全部返回失败)
    return Promise.all(PromiseAll)
  },
  //全选
   checkAllFn({dispatch,getters},params){
    let PromiseAll=[]
    getters.cartInfoList.forEach(e => {
        let promise= dispatch('checkCart',{skuId:e.skuId,isChecked:params})
        PromiseAll.push(promise)
     });
     //收集后统一返回
     return Promise.all(PromiseAll)
  }
};
const getters={
    categoryView(state){
        //至少返回一个空对象
        return state.goodInfo.categoryView || {}
    },
    skuInfo(state){
        return state.goodInfo.skuInfo || {}
    },
    //简化产品信息
    spuSaleAttrList(state){
        return state.goodInfo.spuSaleAttrList || []
    }
};
export default{
    state,
    mutations,
    actions,
    getters
}
